﻿using System;

namespace FRS.Telnet
{
    public class Telnet
    {
        private TelnetClient client;

        /// <summary>Gets whether the we are connected with the device.</summary>
        public bool Connected { get; private set; }

        /// <summary>Login to the specific host.</summary>
        /// <param name="hostname">The hostname.</param>
        /// <param name="user">The user.</param>
        /// <param name="pwd">The PWD.</param>
        /// <param name="timeout">The timeout.</param>
        public void Login(string hostname, string user, string pwd, uint timeout)
        {
            Close();
            try
            {
                client = new TelnetClient(hostname, 1234);
            }
            catch (Exception ex)
            {
                throw new TelnetClientException(TelnetClientException.Errors.ConnectionNotPossible, String.Format("Connection to {0} not possible", hostname), ex);
            }
            client.DisableEcho();
            client.Login(user, pwd);
            Connected = true;
        }
        
        /// <summary>Sends a command to the host.</summary>
        /// <param name="command">The command.</param>
        public string SendCommand(string command)
        {
            client.WriteLine(command);
            return client.Read();
        }

        /// <summary>Closes the connection.</summary>
        public void Close()
        {
            if (client != null)
            {
                client.Close();
                client = null;
                Connected = false;
            }
        }
    }
}
